#!/usr/bin/env python3
import socket
import os
import sys
import re
import subprocess

# 配置参数
INTERFACE = "bond0"
NETPLAN_FILE = f"/etc/netplan/99-{INTERFACE}-static.yaml"
NETMASK = 24
NETWORK_PREFIX = "10.176.64"
GATEWAY = "10.172.64.1"


def get_host_last_three_digits():
    """获取主机名后三位数字"""
    hostname = socket.gethostname()
    digits = re.findall(r"\d+", hostname)
    if not digits:
        print(f"无法从主机名 {hostname} 获取数字")
        sys.exit(1)
    # 使用最后一组数字
    last_three = digits[-1]
    # 取后三位，不够三位补0
    last_three = last_three.zfill(3)[-3:]
    return int(last_three)


def generate_ip():
    """根据主机名生成 IP"""
    last_octet = get_host_last_three_digits()
    if last_octet < 1 or last_octet > 254:
        print(f"生成的 IP 最后一段 {last_octet} 不在合法范围 1-254")
        sys.exit(1)
    return f"{NETWORK_PREFIX}.{last_octet}"


def write_netplan(ip_address):
    """生成 netplan 配置文件"""
    content = f"""\
network:
  version: 2
  renderer: networkd
  ethernets:
    {INTERFACE}:
      dhcp4: no
      addresses: [{ip_address}/{NETMASK}]
      gateway4: {GATEWAY}
      nameservers:
        addresses: [8.8.8.8,8.8.4.4]
"""
    with open(NETPLAN_FILE, "w", encoding="utf-8") as f:
        f.write(content)
    print(f"已写入 netplan 配置: {NETPLAN_FILE}")


def apply_netplan():
    """应用 netplan 配置"""
    subprocess.run(["netplan", "apply"], check=True)
    print(f"已应用 netplan 配置")


def main():
    ip = generate_ip()
    print(f"配置 {INTERFACE} 为静态 IP: {ip}/{NETMASK}, 网关: {GATEWAY}")
    write_netplan(ip)
    apply_netplan()


if __name__ == "__main__":
    main()
